package com.xrit.sunnyday.service.impl;


import com.alibaba.druid.util.StringUtils;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xrit.sunnyday.dao.UserDao;
import com.xrit.sunnyday.entity.PageResult;
import com.xrit.sunnyday.entity.QueryPageBean;
import com.xrit.sunnyday.pojo.User;
import com.xrit.sunnyday.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

@Service(interfaceClass = UserService.class)
public class UserServicelmpl implements UserService{

    @Autowired
    private UserDao userDao;

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        // 使用PageHelper.startPage
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        // 有查询条件的处理, 模糊查询
        if (!StringUtils.isEmpty(queryPageBean.getQueryString())){
            // 拼接%
            queryPageBean.setQueryString("%"+queryPageBean.getQueryString()+"%");
        }
        // 紧接着的查询会被分页
        Page<User> page = userDao.findByCondition(queryPageBean.getQueryString());
        return new PageResult(page.getTotal(),page.getResult());
    }


    /**
     * 添加用户
     * @param user
     * @param roleIds
     */
    @Override
    @Transactional
    public void add(User user, Integer[] roleIds) {
        // 添加用户
        userDao.add(user);
        // 获取用户的id
        Integer userId = user.getId();
        // 遍历角色id, 添加用户与角色的关系
        if(null != roleIds){
            // 有钩选
            for (Integer roleId : roleIds) {
                //添加用户与角色的关系
                userDao.addUserRole(userId,roleId);
            }
        }
    }


    /**
     * 根据登陆用户名称查询用户权限信息
     * @param username
     * @return
     */
    @Override
    public User findByUsername(String username) {
        return userDao.findByUsername(username);
    }
}
